//
//  ExRxTableHeaderView.swift
//  Swift-Example
//
//  Created by apang on 2018/8/8.
//  Copyright © 2018 apang.men All rights reserved.
//

import UIKit

public protocol ExRxTableViewHeaderDelegate {
     func closeSection(open:Bool, section: NSInteger)
}

class ExRxTableHeaderView: UITableViewHeaderFooterView {
    
    var delegate:ExRxTableViewHeaderDelegate?
    
    lazy var titleLabel : UILabel = { ()->UILabel in
        let tmpLabel = UILabel.init()
        tmpLabel.textColor = UIColor.red
        tmpLabel.font = UIFont.systemFont(ofSize: 16)
        tmpLabel.translatesAutoresizingMaskIntoConstraints = false
        tmpLabel.text = "?"
        self.contentView.addSubview(tmpLabel)
        return tmpLabel
    }()
    
    lazy var rowButton : UIButton = { ()->UIButton in
        let tmpBtn = UIButton(type: UIButton.ButtonType.custom)
        tmpBtn.setImage(UIImage(named: "right_row"), for: UIControl.State.normal)
        tmpBtn.setImage(UIImage(named: "down_row"), for: UIControl.State.selected)
        tmpBtn.addTarget(self, action:#selector(buttonClick(_:)), for: UIControl.Event.touchUpInside)
        tmpBtn.translatesAutoresizingMaskIntoConstraints = false
        self.contentView.addSubview(tmpBtn)
        return tmpBtn
    }()
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
//        self.contentView.backgroundColor = UIColor(red: 0.4, green: 0.6, blue: 0.8, alpha: 1)
        self.addSubviewConstraints()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func addSubviewConstraints() {
        self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[titleLabel]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["titleLabel":titleLabel]))
        self.contentView.addConstraint(NSLayoutConstraint.init(item: titleLabel, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.contentView, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: 0))
        self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[rowButton]-(20)-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["rowButton":rowButton]))
        self.contentView.addConstraint(NSLayoutConstraint.init(item: rowButton, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.contentView, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: 0))
    }
    
    @objc func buttonClick(_ button:UIButton) {
        button.isSelected = !button.isSelected
        self.delegate?.closeSection(open: button.isSelected, section: self.tag)
    }

}
